package LeetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class LeetCodeMain1 {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1==null||nums1.length==0){
            int n=nums2.length;
            if (n%2==0){
                int n1=nums2[n/2];
                int n2=nums2[n/2-1];
                return (n1+n2)/2.0;
            }
            return nums2[n/2];
        }
        if (nums2==null||nums2.length==0){
            int num=nums1.length;
            if (num%2==0){
                int n1=nums1[num/2];
                int n2=nums1[num/2-1];
                return (n1+n2)/2.0;
            }
            return nums1[num/2];
        }
        int num1=nums1.length;
        int nmu2=nums2.length;
        int sum=nmu2+num1;
        int j=0;
        int k=0;
        int count=0;
        int flag=-1;
        int[] arr=new int[nmu2+num1];
        if (nums1[num1-1]<=nums2[0]){
            flag=1;
        }else if (nums1[0]>=nums2[nmu2-1]){
            flag=2;
        }
        while (flag==-1&&j<num1&&k<nmu2){
            if (nums1[j]<nums2[k]){
                arr[count]=nums1[j];
                j++;
            }else {
                arr[count]=nums2[k];
                k++;
            }count++;
        }
        if (count!=0){
            if (j>=num1){
                for (int i = count; i < sum; i++) {
                    arr[i]=nums2[k++];
                }
            }else {
                for (int i = count; i < sum; i++) {
                    arr[i]=nums1[j++];
                }
            }
        }else {
            if (flag==1){
                while (count<sum){
                    if (j<num1){
                        arr[count++]=nums1[j++];
                    }else {
                        arr[count++]=nums2[k++];
                    }
                }
            }else {
                while (count<sum){
                    if (k<nmu2){
                        arr[count++]=nums2[k++];
                    }else {
                        arr[count++]=nums1[j++];
                    }
                }
            }
        }
        if (sum%2==0){
            int sum1=arr[sum/2-1];
            int sum2=arr[sum/2];
            return (sum1+sum2)/2.0;
        }else {
            return arr[sum/2];
        }
    }
    public static void main(String[] args) {
        int[] nums1={};
        int[] nums2={2,3};
        double a=findMedianSortedArrays(nums1,nums2);
        System.out.println(a);
    }
}
